﻿using Newtonsoft.Json;
using System.IO;

namespace BDRUtils.Extensions
{
    public static class SerializeExtensions
    {
        /// <summary>
        /// JsonSerializer序列化
        /// </summary>
        /// <param name="item">对象</param>
        public static string ToJsonStr<T>(this T item) => item == null ? null : JsonConvert.SerializeObject(item);

        /// <summary>
        /// JsonSerializer序列化
        /// </summary>
        /// <param name="item">对象</param>
        public static string ToJsonStr<T>(this T item, JsonSerializerSettings setting) => JsonConvert.SerializeObject(item, setting);

        /// <summary>
        /// JsonSerializer反序列化
        /// </summary>
        /// <param name="str">字符串序列</param>
        public static T ToObject<T>(this string str) => string.IsNullOrEmpty(str) ? default(T) : JsonConvert.DeserializeObject<T>(str);

        /// <summary>
        /// JsonSerializer反序列化
        /// </summary>
        /// <param name="str">字符串序列</param>
        public static T ToObject<T>(this string str, JsonSerializerSettings setting) => JsonConvert.DeserializeObject<T>(str, setting);

        /// <summary>
        /// 美化JsonString
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToBeautifyJsonString(this string str)
        {
            var serializer = new JsonSerializer();
            TextReader tr = new StringReader(str);
            var jtr = new JsonTextReader(tr);
            var obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                var textWriter = new StringWriter();
                var jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return str;
            }
        }
    }
}
